package io.renren.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import org.apache.http.client.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AccessTokenUtil {

    @Autowired
    private static RedisTemplate redisTemplate;
    // 小程序唯一凭证，即 AppID
    public static final String appId = "wx22c7cd0dde9319ee";
    // 小程序唯一凭证密钥，即 AppSecret
    public static final String secret = "2cad63c304f1d2192ce780b9d61ae5fb";


    /**
     * 接口调用凭证 access_token
     *
     * @return
     */
    public static String getAccessToken() {
        // 从缓存中获取
        //        ValueOperations valueOperations = redisTemplate.opsForValue();
        //        String accessToken = String.valueOf(valueOperations.get("access_token"));
        //        if (!StringUtils.isEmpty(accessToken) && !"null".equals(accessToken)) {
        //            return accessToken;
        //        }
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        String result = HttpClientUtil.sendHttpGet(accessTokenUrl);
        JSONObject json = JSONUtil.parseObj(result);
        String access_token = String.valueOf(json.get("access_token"));
        Long expires_in = Long.valueOf(String.valueOf(json.get("expires_in")));
        if (StringUtils.isEmpty(access_token)) {
            access_token = "";
        }
        System.out.println("json:" + json.toString());
        // 存redis, 过期时间为7200秒
        //        valueOperations.set("access_token", access_token, expires_in, TimeUnit.SECONDS);
        return access_token;
    }

    public static String getUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        System.out.println("________>:" + url);
        String result = HttpClientUtil.sendHttpGet(url);
        JSONObject json = JSONUtil.parseObj(result);
        String unionid = String.valueOf(json.get("unionid"));

        System.out.println("json:" + unionid);
        return unionid;
    }

    public static void main(String[] args) {
        String accessToken = getAccessToken();
        getUserInfo(accessToken, "oGvNO4zoHI_u214lSfBRVJzPjITw");
    }
}